var express = require('express');
var router = express.Router();
let mongoose = require('mongoose');
//user
// //建立user集合的模型对象(忽略_id)
// let userSchema = new mongoose.Schema({
//   account: String,
//   password: String
// })
// //建立user集合与模型的关系
// mongoose.model('userModel', userSchema, 'user');


//登录
//改为异步，要等待
/* GET users listing. */
router.post('/login', async function (req, res, next) {
  //操作集合,大括号里都不写是查询所有，
  let data = req.body
  let mongore = await mongoose.model('userModel').find({
    account: data.acc,
    password: data.pws,
  });
  console.log(mongore);

  if (mongore.length > 0) {
    res.send({
      code: 200,
      s: req.body,
      mes: `登录成功！`
    });
  } else {
    res.send({
      code: 250,
      s: req.body,
      mes: `登录失败,账号或密码错误！`
    });
  }

  console.log(req.body);
});
//注册
router.post('/register', async function (req, res, next) {
  //实现添加功能 
  let data = req.body
  let mongore1 = await mongoose.model('userModel').find({
    account: data.acc,

  });
  if (mongore1.length > 0) {
    //用户名重复
    res.send({
      code: 350,
      s: req.body,
      mes: `注册失败，用户名重复`
    });
  } else {
    await mongoose.model('userModel').create({
      account: data.acc,
      password: data.pws,
    });
    res.send({
      code: 300,
      s: req.body,
      mes: `注册成功！`
    });
  }

});

//class

//暴露
module.exports = router;